package top.mcwebsite.playandroid.business.tutorial.impl.vm

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import top.mcwebsite.playandroid.business.tutorial.impl.api.TutorialApi
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.mvi.model.Async
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class TutorialViewModel : BaseViewModel<TutorialIntent, TutorialUiState, TutorialUiEffect>(
    TutorialUiState()
) {

    private val tutorialApi = ServiceManager.getService<NetworkService>()
        .createApi<TutorialApi>()


    init {
        viewModelScope.launch {
            setUiState { copy(tutorialsAsync = Async.Loading) }
            try {
                val tutorialsResp = tutorialApi.getTutorials()
                if (tutorialsResp.errorCode != 0) {
                    setUiState { copy(tutorialsAsync = Async.Failed(tutorialsResp.errorMsg)) }
                } else {
                    val data = tutorialsResp.data
                    if (data != null) {
                        setUiState { copy(tutorialsAsync = Async.Success(data)) }
                    } else {
                        setUiState {
                            copy(tutorialsAsync = Async.Failed("数据为空"))
                        }
                    }
                }

            } catch (e: Exception) {
                // 打印日志
                setUiState {
                    copy(tutorialsAsync = Async.Failed("未知错误"))
                }
                throw e
            }
        }
    }

    override fun handleIntent(intent: TutorialIntent) {
        when (intent) {
            is TutorialIntent.RequestToTutorialMenuIntent -> {
                sendUiEffect(TutorialUiEffect.GoToTutorialMenuEffect(intent.tutorialModel))
            }
        }
    }
}